/*  Exercise 4-2. Extend atof to handle scientific notation of the form

   123.45e-6

where a floating-point number may be followed by e or E and an optionally signed exponent.
*/

#include <ctype.h>
#include <stdio.h>
/* atof:  convert string s to double */
double atof(char s[]);

int main()
{
  double d = atof("3.5e111");
  printf("%e \n",d);
}

double atof(char s[])
{
       double val, power, exp;
       int i, sign, expsign, expval;

       for (i = 0; isspace(s[i]); i++)  /* skip white space */
           ;
       sign = (s[i] == '-') ? -1 : 1;
       if (s[i] == '+' || s[i] == '-')
           i++;
       for (val = 0.0; isdigit(s[i]); i++)
           val = 10.0 * val + (s[i] - '0');
       if (s[i] == '.')
           i++;
       for (power = 1.0; isdigit(s[i]); i++) {
           val = 10.0 * val + (s[i] - '0');
           power *= 10;
       }

	  if ((s[i] == 'e') || (s[i] == 'E'))
        {
		i++;

		if (s[i]=='-')
		  {
		    expsign = 0.0;
		    i++;
		  }
		else expsign=1.0;
		
		exp = 1;

		if (isdigit(s[i]))

	     for (expval = 0.0; isdigit(s[i]); i++)
			expval = 10.0 * expval + (s[i] - '0');

		for (int j=0; j<expval; j++)
		 {
		   if (expsign) exp *= 10.0;
		   else exp /= 10.0;
		 }
	    }
	  
       return ((sign * val) / power) * exp;
}
